import ExportUtil from '@/components/util/exportUtil.js';
import GridCard from '@/components/util/GridCard.js';
import ChartDataUtil from '@/components/util/chartDataUtil.js';
import CardStyleDialog from '@/components/dialog/CardStyleDialog';
import BgDialog from '@/components/dialog/BgDialog';
import SearchChartDialog from '@/components/dialog/SearchChartDialog';
import ChartTypeList from '@/components/data/chartType.js';

export default {
  name: 'DashBoard',
  props: {
    langType: {
      type: String,
      default: window.localStorage.getItem('langType'),
    },
  },
  components: {
    'bg-dialog': BgDialog,
    'card-style-dialog': CardStyleDialog,
    'search-chart-dialog': SearchChartDialog,
  },
  data: () => ({
    label: {
      templateTitle: { zh: '模板标题', en: 'templateTitle' },
      titleError: { zh: '请填写至少两个字的标题!', en: 'Please input title of at least 2 words!' },
      dashboard: { zh: '仪表板', en: 'Dashboard' },
      delTip: {
        zh: '请问是否删除该图表卡?',
        en: 'Are you sure to delete this chart card?',
      },
      chart: { zh: '图表ID:', en: 'ChartID:' },
      ok: { zh: '确定', en: 'OK' },
      no: { zh: '取消', en: 'cancel' },
      refresh: { zh: '刷新', en: 'REFRESH' },
      view: { zh: '预览', en: 'PREVIEW' },
      bgStyle: { zh: '背景样式', en: 'bgStyle' },

      addCard: { zh: '添加卡片', en: 'AddCard' },
      create: { zh: '新建', en: 'CREATE' },
      save: { zh: '保存', en: 'SAVE' },
      saveFail: { zh: '保存模板失败！', en: 'Fail to save Template!' },
      saveOK: { zh: '保存模板成功！', en: 'Succeed to save Template!' },
      update: { zh: '更新', en: 'UPDATE' },
      updateFail: { zh: '更新模板失败!', en: 'Fail to update Template!' },
      updateOK: { zh: '更新模板成功!', en: 'Succeed to update Template!' },
      export: { zh: '导出', en: 'EXPORT' },
      exitFullscreen: { zh: '退出全屏', en: 'EXIT FULL SCREEN' },
      fullScreen: { zh: '全屏', en: 'FULL SCREEN' },

      chartFail: { zh: '获取图表失败!', en: 'Fail to load chart!' },
      loadDataFail: { zh: '获取数据失败!', en: 'Fail to load data package!' },
      addCardRepeat: {
        zh: '该图表已存在，不可重复添加!',
        en: "The chart is exist so it can't be added repeatedly",
      },
      templateFail: { zh: '获取模板失败!', en: 'Fail to load Template' },
    },
    //图表类型
    chartTypeList: ChartTypeList,
    //拖拽板面
    gridCard:null,
    //是否全屏
    isFullscreen: false, 
    //卡片数据列表
    cardList: [], 
    //图表列表
    chartList: [], 
     //卡片样式列表
    cardStyleList: [],
    //删除图表
    showDel: false,
    //选中卡片的chart_id
    selectId: 0,
    //选中卡片索引
    selectIdx: 0,

    //提示框显示
    isAlert: false,
    //提示信息
    alertTip: '',
    //是否显示卡片样式设置dialog
    isCardStyle: false,
    cardStyle: { card: {}, title: {}, content: {} },
    //是否显示添加图表卡dialog
    isAddCard: false,
    //模板信息
    chartTemplate: {
      template_id: '',
      title: '',
    },
    //背景样式dialog
    isBgStyle: false,
    //背景样式
    bgStyle: {
      bgType: 'purity',
      gradient: 'top',
      gradientColor1: '#FFFFFF',
      gradientColor2: '#FFFFFF',
      picture: '',
      picUrl: '',

      isUrlPic: false,
      result: '',
    },
    //暂存模板数据
    chartTempList:[],
  }),
  watch: {},
  methods: {
    //预览模板
    viewBoard(){
      var idx=this.chartTemplate.template_id;
      
      window.open(
        window.location.origin + window.location.pathname + '#/leader-detail?tempId=' + idx
      );
    },
    /**刷新板面 */
    refreshBoard() {
      var id=this.chartTemplate.template_id;
      this.cardList = [];
      this.cardStyleList = [];
      this.chartList = [];
      this.gridCard.removeAllCard(); 
      this.loadTemplate(id);
      
    },

    //全屏
    fullScreen() {
      var el = document.getElementById('the_dashboard');

      if (!this.isFullscreen) {
        //进入全屏,多重短路表达式
        (el.requestFullscreen && el.requestFullscreen()) ||
          (el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
          (el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
          (el.msRequestFullscreen && el.msRequestFullscreen());
      } else {
        //退出全屏,三目运算符
        document.exitFullscreen
          ? document.exitFullscreen()
          : document.webkitExitFullscreen
          ? document.webkitExitFullscreen()
          : document.mozCancelFullScreen
          ? document.mozCancelFullScreen()
          : '';
      }
      this.isFullscreen = this.isFullscreen ? false : true;
      that.resizeBoard();
    },
    /**
     * 新建模板
     */
    newTemplate() {
      this.chartTemplate = {
        template_id: '',
        title: '',
      };
      this.cardStyle = { card: {}, title: {}, content: {} };
      this.bgStyle = {
        bgType: 'purity',
        gradient: 'top',
        gradientColor1: '#FFFFFF',
        gradientColor2: '#FFFFFF',
        picture: '',
        picUrl: '',
        isUrlPic: false,
        result: '',
      };
      this.cardList = [];
      this.cardStyleList = [];
      this.chartList = [];
      this.gridCard.removeAllCard();      
      window.location.hash = '#/dashboard';
    },
    /**获取模板数据 */
    getPostData() {
      
      var data = {},
      chartList=[];
     
      for (var i = 0; i < this.cardList.length; i++) {        
        var item = this.cardList[i]; 
        var dataset = document.getElementById('dashboard_chart_card' + item.chart_id).parentElement.dataset;       
        chartList.push({chart_id:item.chart_id,data_id:item.data_id,style:this.cardStyleList[i],pos:dataset});
      }     
      data.chartList = JSON.stringify(chartList);
      data.title = encodeURI(this.chartTemplate.title);
      data.bg = JSON.stringify(this.bgStyle);
      data.userId = JSON.parse(window.localStorage.getItem("carweb_user")).userId;
      return data;
    },
    /**保存板面 */
    saveBoard() {
      if (!this.chartTemplate.title||this.chartTemplate.title.length<2) {
        this.alertTip = this.getLangText(this.label.titleError);
        this.isAlert = true;
        return ;
      }
      var that = this;
      var data = this.getPostData();
      $.post(this.API.saveTemplate, data, function(res) {
        if (res.errCode == 0) {
          that.chartTemplate.template_id = res.data;
          that.alertTip = that.getLangText(that.label.saveOK);
        } else {
          that.alertTip = that.getLangText(that.label.saveFail);
        }
        that.isAlert = true;
      });
    },
    /**更新板面 */
    updateBoard() {
      if (!this.chartTemplate.title||this.chartTemplate.title.length<2) {
        this.alertTip = this.getLangText(this.label.titleError);
        this.isAlert = true;
        return ;
      }
      var that = this;
      var data = this.getPostData();
      data.tempId = this.chartTemplate.template_id;
      $.post(this.API.updateTemplate, data, function(res) {
        if (res.errCode == 0) {
          that.alertTip = that.getLangText(that.label.updateOK);
        } else {
          that.alertTip = that.getLangText(that.label.updateFail);
        }
        that.isAlert = true;
      });
    },
//导出模板
    exportBoard() {
      var that=this;
      $.get(this.API.staticPath+'leader_template.html',function(html){
        html=html.replace('_template_',that.gridCard.exportHtml());
        html=html.replace('_grid_title_',that.chartTemplate.title);
        ExportUtil.exportFile(html,'.html','text/html');
      })
    },
//编辑图表
    showDetail(item) {
      window.open(
        window.location.origin + window.location.pathname + '#/charteditor?chartId=' + item.chart_id
      );
    },
//背景样式dialog
    createBg(style) {
      this.bgStyle = style;
    },
    /** 检查图表是否重复添加*/
    checkChartRepeated(id) {
      for (var i = 0; i < this.cardList.length; i++) {
        if (id == this.cardList[i].chart_id) {
          this.alertTip = this.getLangText(this.label.addCardRepeat);
          this.isAlert = true;
          return false;
        }
      }
      return true;
    },
    
    //添加图表
    doAddCard(id) {
      if (!this.checkChartRepeated(id)) return;
      var that = this;
      ChartDataUtil.getChartAndData(id,function(option){
        if(option){
          that.cardList.push(option);
          that.cardStyleList.push({ card: {}, title: {}, content: {} });
          var html = that.makeCardByChart(option);
          that.gridCard.addCard(html,{sizex:3,sizey:3,col:1,row:1});
          setTimeout(function(){
            ChartDataUtil.setChart(
              'dashboard_chart' + option.chart_id,
              option,
              function(chart) {
                that.chartList.push(chart);
              }
            );
          },200)
         
        }else{
          that.alertTip = that.getLangText(that.label.loadDataFail);
          that.isAlert = true;
        }
      });
      
    },
    //制作图表
    makeCardByChart(chartOp) {
      //写入标题
      var card=document.getElementById('dashboard_chart_card_idx_');
      var header = card.children[0].children[0];
      header.innerText = chartOp.title;
      
      //设置元素id
      var html = card.outerHTML + '';
      html = html.replace(/_idx_/g, chartOp.chart_id);
      html = html.replace('none', '');
      return html;
    },
    /**设置卡片样式 */
    setCardStyle(style) {
      //设置卡片样式
      var card = document.getElementById('dashboard_chart_card' + this.selectId);
      this.setItemStyle(card, style.card);

      //设置标题样式
      var header = card.children[0].children[0];

      header.style.fontSize = style.title.fontSize;
      header.style.fontWeight = style.title.fontWeight;
      header.style.color = style.title.fontColor;
      header.style.textAlign = style.title.textAlign;
      this.setItemStyle(header, style.title);
      //设置内容样式
      var content = card.children[1];
      this.setItemStyle(content, style.content);
      //保存卡片样式
      this.cardStyleList[this.selectIdx] = style;
      //调整图表大小
      this.resizeChart(this.selectIdx);
    },
    //设置卡片样式
    setCardStyle1(style, id) {
      //设置卡片样式
      var card = document.getElementById('dashboard_chart_card' + id);
      this.setItemStyle(card, style.card);

      //设置标题样式
      var header = card.children[0].children[0];
      header.style.fontSize = style.title.fontSize;
      header.style.fontWeight = style.title.fontWeight;
      header.style.color = style.title.fontColor;
      header.style.textAlign = style.title.textAlign;
      this.setItemStyle(header, style.title);
      //设置内容样式
      var content = card.children[1];
      this.setItemStyle(content, style.content);
    },
    //设置元素样式
    setItemStyle(elmt, style) {
      if (!elmt || !style || style == { card: {}, title: {}, content: {} }) return;
      elmt.style.background = style.color ? style.color : 'transparent';
      elmt.style.borderColor = style.borderColor ? style.borderColor : 'transparent';
      elmt.style.borderWidth = style.borderWidth ? style.borderWidth : 0;
      elmt.style.borderStyle = style.borderType ? style.borderType : 'solid';
      elmt.style.boxShadow =
        style.shadowOffsetX +
        ' ' +
        style.shadowOffsetY +
        ' ' +
        style.shadowBlur +
        ' ' +
        style.shadowColor;
      elmt.style.opacity = style.opacity ? style.opacity : 1;
      elmt.style.borderRadius = style.borderRadius ? style.borderRadius : 0;
    },
 
    //刷新图表
    refreshCard(id) {
      var that = this;
      ChartDataUtil.getChartAndData(id, function(option) {
        if (option) {
          that.cardList[that.selectIdx] = option;
          //设置卡片标题
          var header = document.getElementById('dashboard_chart_card' + option.chart_id).children[0]
            .children[0];
          header.innerText = option.title;
          if (that.chartList[that.selectIdx]) {
            that.chartList[that.selectIdx].dispose();
          }
          ChartDataUtil.setChart(
            'dashboard_chart' + option.chart_id,
            option,
            function(chart) {
              that.chartList[that.selectIdx] = chart;
            }
          );
        } else {
          that.alertTip = that.getLangText(that.label.chartFail);
          that.isAlert = true;
        }
      });
    },
    //调整图表大小
    resizeChart(id) {
      var chart = this.chartList[id];
      chart.resize(chart.getDom().offsetWidth, chart.getDom().offsetHeight);
    },
 
    /**删除卡片 */
    onDelConfirm() {
      this.cardList.splice(this.selectIdx, 1);
      this.chartList.splice(this.selectIdx, 1);
      this.cardStyleList.splice(this.selectIdx, 1);
      this.gridCard.removeCardByIdx(this.selectIdx);
    },
      

    //添加模板卡片
    addTemplateCard(idx) {
      var that = this;
      if (idx < this.chartTempList.length) {
        var chart_id = this.chartTempList[idx].chart_id,
          style = this.chartTempList[idx].style,
          pos = this.chartTempList[idx].pos;

          ChartDataUtil.getChartAndData(chart_id, function(option) {
            if(option){
            that.cardList.push(option);
            that.cardStyleList.push(style);
            var html = that.makeCardByChart(option);
            that.gridCard.addCard(html,pos);           
            ChartDataUtil.setChart(
              'dashboard_chart' + option.chart_id,
              option,
              function(chart) {
                that.chartList.push(chart); 
                that.setCardStyle1(style, option.chart_id); 
              }
            );
          }else{
            that.alertTip = that.getLangText(that.label.loadDataFail)+'\n'+'ID:'+chart_id;
                that.isAlert = true;
                
          }
          if(idx+1< that.chartTempList.length){
            setTimeout(function() {
              that.addTemplateCard(idx + 1);
            }, 2000);
          }else{
            document.getElementById('wait_page').style.display='none';
          }

          });
        
      } else {
      
        document.getElementById('wait_page').style.display='none';
      }
    },

    /**根据id获取模板信息 */
    loadTemplate(id) {
      var that = this;
     
      ChartDataUtil.getTemplate(id,function(option){
        if(option){
          that.chartTemplate.title=option.title;
          that.bgStyle=option.bg;
          that.chartTempList=option.chartList;
          document.getElementById('wait_page').style.display='flex';
          that.addTemplateCard(0);
        }else{
          that.alertTip = that.getLangText(that.label.templateFail);
          that.isAlert = true;
        }
      });     
    },
//创建拖拽板面
    createGrid() {
      var that = this;
      this.gridCard=new GridCard('dashboard_grid',{
        actionColor:'var(--md-theme-default-accent, rgba(0, 0, 0, 0.12))',
        actionCallback:function(e,card){
        
          var idx=card.children[0].dataset.idx;
              that.selectId=idx;
              for(var i=0;i<that.cardList.length;i++){
                if(that.selectId==that.cardList[i].chart_id){
                  that.selectIdx=i;
                  break;
                }
              }
          if (e.target.className == 'iconfont iconshanchu'&&idx) {
            //删除
            that.showDel = true;
            return true;
          } else if (e.target.className == 'iconfont iconPencil'&&idx) {
            //编辑图表
            window.open(
              window.location.origin + window.location.pathname + '#/charteditor?chartId=' + idx
            );
            return true;
          } else if (e.target.className == 'iconfont iconyanse'&&idx) {
            //卡片样式
            
            that.cardStyle =JSON.parse(JSON.stringify(that.cardStyleList[that.selectIdx]));
            that.isCardStyle = true;
            return true;
          } else if (e.target.className == 'iconfont iconrefresh'&&idx) {
            //刷新
            that.refreshCard(idx);
            return true;
          }          
          return false;          
        },
        resizeCallback:function(card){
        that.selectId=card.children[0].dataset.idx;
        for(var i=0;i<that.cardList.length;i++){
          if(that.selectId==that.cardList[i].chart_id){
            that.selectIdx=i;
            break;
          }
        }
        that.resizeChart(that.selectIdx);

      }});
      
      document.getElementsByTagName('body')[0].onresize = function() {
        that.resizeBoard();
      };
      setTimeout(function() {
        var address = window.location.hash;
        if (address.indexOf('tempId') >= 0) {
          var id=address.split('=')[1];
          that.chartTemplate.template_id = id;
          that.loadTemplate(id);
        }
      }, 1000);
    },
    //调整板面大小
    resizeBoard(){
      var that=this;
      setTimeout(function(){
        that.gridCard.resizeGrid();
        for (var i = 0; i < that.chartList.length; i++) {
          that.resizeChart(i);
        }
      },100)
     
      
    }
  },
  mounted() {
    this.createGrid();
  },
};
